<?php

declare (strict_types=1);

namespace app\store\controller\presalesCustomer;

use app\store\controller\Controller;
use app\store\model\UploadFile as UploadFileModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;
use think\response\Json;

/**
 * Class Customer
 * @package app\store\controller\customer
 */
class Index extends Controller
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\store\model\presalesCustomer\PresalesCustomer;
    }

    public function valueTrimFormat($value)
    {
        return $value ? trim((string)$value) : '';
    }

    public function import($fileId)
    {
        $model = new UploadFileModel;
        $fileInfo = $model->where(['file_id' => $fileId])->find();
        $filePath = ROOT_PATH() . 'public/uploads/' . $fileInfo->file_path;
        $spreadsheet = IOFactory::load($filePath);
        $list = $spreadsheet->getActiveSheet()->toArray();
        $error = "";
        $addData = [];
        foreach ($list as $index => $item) {
            if ($index > 0) {
                $i = $index + 1;
                if (count($item) != 11) {
                    $error = "第{$i}行错误：导入文件格式错误！";
                    break;
                }

                $full_name = $this->valueTrimFormat($item[0] ?? '');
                if (!$full_name) {
                    $error = "第{$i}行错误：客户姓名为空！";
                    break;
                }

                $mobile = $this->valueTrimFormat($item[4] ?? '');
                if (!$mobile) {
                    $error = "第{$i}行错误：手机号码为空！";
                    break;
                }
                //手机号码排重
                if ($this->model->byMobile($mobile)) {
                    $error = "第{$i}行错误：手机号码已存在，请勿重复导入！";
                    break;
                }

                $source = $this->valueTrimFormat($item[6] ?? '');
                if (!$source) {
                    $error = "第{$i}行错误：客户来源为空！";
                    break;
                }
                //查找来源
                $source_id = (new \app\store\model\presalesCustomer\Source())->findSourceId($source);
                if (!$source_id) {
                    $error = "第{$i}行错误：未找到指定的客户来源！";
                    break;
                }
                $customer_type_id = 0;
                $customer_type = $this->valueTrimFormat($item[7] ?? '');
                if ($customer_type) {
                    //查找客户类型
                    $customer_type_id = (new \app\store\model\presalesCustomer\Type())->findCustomerTypeId($customer_type);
                    if (!$customer_type_id) {
                        $error = "第{$i}行错误：未找到指定的客户类型！";
                        break;
                    }
                } else {
                    //使用默认类型
                    $default_type = (new \app\store\model\presalesCustomer\Type())->getDefaultType();
                    if ($default_type) {
                        $customer_type_id = $default_type->pct_id;
                    }
                }

                $addData[] = [
                    'full_name' => $full_name,
                    'idnumber' => $this->valueTrimFormat($item[1] ?? ''),
                    'corporate_name' => $this->valueTrimFormat($item[2] ?? ''),
                    'signatory' => $this->valueTrimFormat($item[3] ?? ''),
                    'mobile' => $mobile,
                    'region' => $this->valueTrimFormat($item[5] ?? ''),
                    'pcs_id' => $source_id,
                    'pct_id' => $customer_type_id,
                    'other_contacts' => $this->valueTrimFormat($item[8] ?? ''),
                    'other_contacts_mobile' => $this->valueTrimFormat($item[9] ?? ''),
                    'illustrate' => $this->valueTrimFormat($item[10] ?? ''),
                    'create_time' => time(),
                    'store_id' => $this->storeId,
                    'store_user_id' => $this->store['user']['store_user_id'],
                ];
            }
        }
        if ($error) {
            return $this->renderError($error);
        }
        $this->model->insertAll($addData);
        return $this->renderSuccess('导入成功');
    }


    /**
     * 添加
     * @return Json
     */
    public function add(): Json
    {
        if ($this->model->adds($this->postForm(), $this->store)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($this->model->getError() ?: '添加失败');
    }

    /**
     * 更新
     * @param int $apiId
     * @return Json
     */
    public function batch_edit(array $apiId): Json
    {
        $model = $this->model;
        // 更新记录
        if ($model->batch_edit($apiId, $this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

//
//    public function all(): Json
//    {
//        $list = $this->model->all($this->request->param(), $this->store);
//        return $this->renderSuccess(compact('list'));
//    }

}
